//
//  CIDetector-Face.m
//  CoreImageDemo
//
//  Created by zero on 2017/6/12.
//  Copyright © 2017年 zero. All rights reserved.
//

#import "CIDetector-Face.h"

@interface CIDetector_Face ()
@property (nonatomic,strong) UIImageView* imageView;
@property (nonatomic,strong) UIImage* image;
@end

@implementation CIDetector_Face

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.image = [UIImage imageNamed:@"p199012.jpg"];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.imageView];
    [self action_recognitionFace];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private

- (void)action_recognitionFace{
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage* image = [CIImage imageWithCGImage:self.imageView.image.CGImage];
    
    NSDictionary* param = [NSDictionary dictionaryWithObject:CIDetectorAccuracyHigh forKey:CIDetectorAccuracy];
    CIDetector* faceDetector = [CIDetector detectorOfType:CIDetectorTypeFace context:context options:param];
    
    NSArray* featureArray = [faceDetector featuresInImage:image];
    
    for (CIFaceFeature* feature in featureArray) {
        
        NSLog(@"%@",NSStringFromCGRect(feature.bounds));
        if(feature.hasLeftEyePosition){
            [self.imageView addSubview:[self markView:CGRectMake(0, 0, 20, 20) Center:feature.leftEyePosition]];
        }
        if(feature.hasRightEyePosition){
            [self.imageView addSubview:[self markView:CGRectMake(0, 0, 20, 20) Center:feature.rightEyePosition]];
        }
        if (feature.hasMouthPosition) {
            [self.imageView addSubview:[self markView:CGRectMake(0, 0, 80, 20) Center:feature.mouthPosition]];
            
        }
    }
}

- (UIView*)markView:(CGRect)frame Center:(CGPoint)point{
    UIView* view = [[UIView alloc]initWithFrame:frame];
    view.center = CGPointMake(point.x, self.image.size.height-point.y);
    view.layer.borderColor = [UIColor redColor].CGColor;
    view.layer.borderWidth = 1;
    return view;
}

#pragma mark - Get
- (UIImageView*)imageView{
    if(!_imageView){
//        _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)/2.0)];
//        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        _imageView = [[UIImageView alloc]initWithImage:self.image];
        _imageView.frame = CGRectMake(0, 0, self.image.size.width, self.image.size.height);
    }
    return _imageView;
}

@end
